package com.fy.proj5_permission_transaction_cache.interceptor;

import com.fy.proj5_permission_transaction_cache.service.PageVisitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 页面访问拦截器，用于记录页面访问次数
 */
@Component
public class PageVisitInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(PageVisitInterceptor.class);
    
    @Autowired
    private PageVisitService pageVisitService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 只记录页面访问，不记录API请求
        String uri = request.getRequestURI();
        
        // 排除API请求、静态资源和错误页面
        if (uri.startsWith("/api/") || uri.startsWith("/static/") || uri.startsWith("/error") || uri.contains(".")) {
            return true;
        }
        
        // 获取页面名称（去除上下文路径）
        String contextPath = request.getContextPath();
        String pageName = uri.substring(contextPath.length());
        
        // 如果页面名为空，设置为首页
        if (pageName.isEmpty() || pageName.equals("/")) {
            pageName = "/index";
        }
        
        // 记录页面访问
        pageVisitService.recordVisit(pageName);
        
        // 获取客户端IP并记录
        String ip = getClientIpAddress(request);
        pageVisitService.recordIpVisit(pageName, ip);
        
        logger.debug("Page visit recorded: {} from IP: {}", pageName, ip);
        return true;
    }
    
    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        // 如果是多个IP，取第一个
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        
        return ip;
    }
}